import random
import sys
# Need to write script to build large database file for testing.

first_names = ["Alice", "Bob", "Carry", "Dave", "Ernie", "Frodo", "George", "Harry", "Irene", "Janet", "Kelly", "Leroy", "Mike", "Nora", "Oscar", "Peter", "Quinn", "Rachel", "Steve", "Tina", "Unix", "Victor", "Wendy", "Xavier", "Yvette", "Zachary"]

last_names = ["Smith", "Jones", "Thompson", "Foo", "Carter", "Nixon", "Culpepper", "Masterson", "Pitt", "Mayfield", "Wakerly", "Jensen", "Gillete", "Li", "Jenkins", "Tilman", "Cotes", "Abercrombie", "Rutherford", "Johnson", "Edison", "Powell", "Butler", "Lucas", "Chapman", "Browne", "Tomkins", "Milton", "Payne", "Bishop", "Little", "Borden", "Scott", "Newton", "Bennet", "Stilman", "Wood", "Pierce", "Warren"]

src_images = ["test.jpg", "test2.jpg", "test3.jpg", "test4.jpg", "test5.jpg", "test6.jpg", "test7.jpg", "test8.jpg", "test9.jpg"]

def gen_db(filename, resource_path, num_cases):
	patients = []
	patient_ids = []
	images = []
	image_ids = []
	cases = []
	case_to_imgs = []

	# Make N patients
	for i in range(1, num_cases+1):
		fname = random.choice(first_names)
		lname = random.choice(last_names)
		patient_ids.append(i)
		patients.append([i, fname, lname])

	# Make a bunch of image references
	total_images = random.randint(num_cases+1, num_cases*2)
	for i in range(1, total_images):
		images.append([i, "Image %d" % (i), resource_path+"/"+random.choice(src_images)])
		image_ids.append(i)

	# Make some cases
	for i in range(1, num_cases+1):
		cases.append([i, "Case %d" % (i), random.choice(patient_ids)])

	# Add some images to the cases
	for i in range(1, num_cases+1):
		img_idx = random.randint(1, len(image_ids)-1)
		image_id = image_ids[img_idx]
		del image_ids[img_idx]
		case_to_imgs.append([i, image_id])

	for i in image_ids:
		case_to_imgs.append([random.randint(1, num_cases), i])

	# Output the database
	f = open(filename, "w")
	f.write(">PATIENTS\n")
	f.write("|patientid,firstname,lastname\n")
	for patient in patients:
		f.write("%d,%s,%s\n" % tuple(patient))
	f.write(">CASES\n")
	f.write("|caseid,casename,patientid,assigned\n")
	for case in cases:
		f.write("%d,%s,%d,false\n" % tuple(case))
	f.write(">IMAGES\n")
	f.write("|imageid,imagedesc,imagepath\n")
	for image in images:
		f.write("%d,%s,%s\n" % tuple(image))
	f.write(">CASE_IMAGE\n")
	f.write("|caseid,imageid\n")
	for ci in case_to_imgs:
		f.write("%d,%d\n" % tuple(ci))
	f.close()

if __name__=="__main__":
	random.seed()
	gen_db(sys.argv[1], "resource/images", int(sys.argv[2]))
